package com.noteit.action;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;

import com.noteit.bean.Noteit;
import com.noteit.dao.NoteitDAO;
import com.opensymphony.xwork2.ActionSupport;  
import com.opensymphony.xwork2.ognl.OgnlValueStack;

public class NoteitAction extends ActionSupport implements SessionAware,RequestAware  {

	private static final long serialVersionUID = -2414674766097689706L;
	private Map<String, Object> sessionMap;
	private Map<String, Object> requestMap;
	@Autowired
	private NoteitDAO noteitDao;
	public int id, importance;
	private Noteit ni;
	private String userName, english, englishE; //english:音譯  englishE:英語
	private String property, sentence;//詞性 /例句
	private String chinese, chineses;//   繁/簡
	private String japanese, japaneses;// 平假名/片假名
	private String picture;
	private String location;
	private Date createdate = null, updatedate = null, deletedate = null;
	private String deleteUserName, deleteFlag, checkDataIsNew;
	//for location
	private String inLatLng;
	
	
	//for QUERY
	private String createdateBgnStr, createdateEndStr;
	private Date createdateBgn, createdateEnd;
	private String updatedateBgnStr, updatedateEndStr;
	private Date updatedateBgn, updatedateEnd;
	private String deletedateBgnStr, deletedateEndStr;
	private Date deletedateBgn, deletedateEnd;
	private String url;

	public String getUrl()
	{
	 return url;
	}
	
	public String deleteUploadImage(){
		OgnlValueStack stack = (OgnlValueStack) requestMap.get("struts.valueStack");
		HttpServletRequest request = (HttpServletRequest) stack.getContext().get(StrutsStatics.HTTP_REQUEST);
		userName = (String) ServletActionContext.getRequest().getSession().getAttribute("loggedInUser");
		String deleteImage = request.getParameter("picture");
		String userCurrentViewId = request.getParameter("id");
		checkDataIsNew = request.getParameter("checkDataIsNew");
		
		if(checkDataIsNew.equalsIgnoreCase("Y")){
			if(deleteImage.length()>0 && deleteImage!=null){
				//刪除實體位置資料/opt/NoteITService/cjfan2005/1023145732098.jpg
				System.out.println("deleteImage="+deleteImage);
				File f1 = new File(deleteImage);
				f1.delete();
			}
			return "success_in_noteit_jsp";
		}else{
			if(deleteImage.length()>0 && deleteImage!=null){
				//刪除實體位置資料/opt/NoteITService/cjfan2005/1023145732098.jpg
				System.out.println("deleteImage="+deleteImage);
				try {
					File f1 = new File(deleteImage);
					f1.delete();
				} catch (Exception e) {
					e.getMessage();
				}  
				
				//還必須清空資料庫紀錄位置:
				try {
					noteitDao.updateUploadLocation(userName, deleteImage);
				} catch (Exception e) {
					e.getMessage();
				}
				url = "InitModifyNoteitAction.do?id="+userCurrentViewId;
				
				
			}
			return "redirect";
		}
	}
	
	public String wordsPool(){
		List<Noteit> noteitList = null;
		userName = (String) ServletActionContext.getRequest().getSession().getAttribute("loggedInUser");  
		deleteFlag = "N";
		Noteit ni = new Noteit();
		if ((english != null && !english.isEmpty())) {
			ni.setEnglish(english);
		}
		if ((chinese != null && !chinese.isEmpty())) {
			ni.setChinese(chinese);
		}
		if ((userName != null && !userName.isEmpty())) {
			ni.setUserName(userName);
		}
		if ((deleteFlag != null && !deleteFlag.isEmpty())) {
			ni.setDeleteFlag(deleteFlag);
		}
		//createdate
		if ((createdateBgnStr != null && !createdateBgnStr.isEmpty())) {
			DateFormat df = DateFormat.getDateInstance();
			try {
				createdateBgn = df.parse(createdateBgnStr);
			} catch (ParseException e) {
				System.out.println("createdateBgn err:"+e.getMessage());
			}
		}
		if ((createdateEndStr != null && !createdateEndStr.isEmpty())) {
			DateFormat df = DateFormat.getDateInstance();
			try {
				createdateEnd = df.parse(createdateEndStr);
			} catch (ParseException e) {
				System.out.println("createdateEnd err :"+e.getMessage());
			}
		}
		//updatedate
		if ((updatedateBgnStr != null && !updatedateBgnStr.isEmpty())) {
			DateFormat df = DateFormat.getDateInstance();
			try {
				updatedateBgn = df.parse(updatedateBgnStr);
			} catch (ParseException e) {
				System.out.println("updatedateBgn err:"+e.getMessage());
			}
		}
		if ((updatedateEndStr != null && !updatedateEndStr.isEmpty())) {
			DateFormat df = DateFormat.getDateInstance();
			try {
				updatedateEnd = df.parse(updatedateEndStr);
			} catch (ParseException e) {
				System.out.println("updatedateEnd err:"+e.getMessage());
			}
		}
		//noteitList = noteitDao.wordsPpoolAll();
		noteitList = noteitDao.wordsPoolCondition(ni,createdateBgn,createdateEnd,updatedateBgn,updatedateEnd);
		sessionMap.put("noteitList", noteitList);
		return "success";
	}
	
	public String wordsPoolDelHistory(){
		List<Noteit> noteitDelHistoryList = null;
		userName = (String) ServletActionContext.getRequest().getSession().getAttribute("loggedInUser");
		deleteFlag = "Y";
		Noteit ni = new Noteit();
		if ((english != null && !english.isEmpty())) {
			ni.setEnglish(english);
		}
		if ((chinese != null && !chinese.isEmpty())) {
			ni.setChinese(chinese);
		}
		if ((userName != null && !userName.isEmpty())) {
			ni.setUserName(userName);
		}
		if ((deleteFlag != null && !deleteFlag.isEmpty())) {
			ni.setDeleteFlag(deleteFlag);
		}
		//createdate
		if ((createdateBgnStr != null && !createdateBgnStr.isEmpty())) {
			DateFormat df = DateFormat.getDateInstance();
			try {
				createdateBgn = df.parse(createdateBgnStr);
			} catch (ParseException e) {
				System.out.println("createdateBgn err:"+e.getMessage());
			}
		}
		if ((createdateEndStr != null && !createdateEndStr.isEmpty())) {
			DateFormat df = DateFormat.getDateInstance();
			try {
				createdateEnd = df.parse(createdateEndStr);
			} catch (ParseException e) {
				System.out.println("createdateEnd err :"+e.getMessage());
			}
		}
		//deletedate
		if ((deletedateBgnStr != null && !deletedateBgnStr.isEmpty())) {
			DateFormat df = DateFormat.getDateInstance();
			try {
				deletedateBgn = df.parse(deletedateBgnStr);
			} catch (ParseException e) {
				System.out.println("deletedateBgn err:"+e.getMessage());
			}
		}
		if ((deletedateEndStr != null && !deletedateEndStr.isEmpty())) {
			DateFormat df = DateFormat.getDateInstance();
			try {
				deletedateEnd = df.parse(deletedateEndStr);
			} catch (ParseException e) {
				System.out.println("deletedateEnd err :"+e.getMessage());
			}
		}
		noteitDelHistoryList = noteitDao.wordsPoolDelHistory(ni,createdateBgn,createdateEnd,deletedateBgn,deletedateEnd);
		sessionMap.put("noteitDeleteHistoryList", noteitDelHistoryList);
		return "success";
	}
	
	public String saveNoteit(){
		OgnlValueStack stack = (OgnlValueStack) requestMap.get("struts.valueStack");
		HttpServletRequest request = (HttpServletRequest) stack.getContext().get(StrutsStatics.HTTP_REQUEST);

		userName = (String) ServletActionContext.getRequest().getSession().getAttribute("loggedInUser");  
		checkDataIsNew = request.getParameter("checkDataIsNew");
		Noteit ni = new Noteit();
		if(checkDataIsNew.equalsIgnoreCase("Y")){
			ni.setUserName(userName);
			ni.setChinese(chinese);
			ni.setChineses(chineses);
			ni.setEnglishE(englishE);
			ni.setEnglish(english);
			ni.setJapanese(japanese);
			ni.setJapaneses(japaneses);
			ni.setPicture((picture.length()>4)?picture:null);
			ni.setLocation(inLatLng.replaceAll("[(*)]", ""));//去掉不要"()"符號，原始檔：(12.123,123.12)
			ni.setImportance(importance);
			ni.setCreatedate(new Date());
			ni.setDeleteFlag("N");
			ni.setSentence(sentence);
			ni.setProperty(property);
			
			try {
				noteitDao.saveNoteit(ni);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "success_addNew";
		}else if(checkDataIsNew.equalsIgnoreCase("N")){
			ni.setId(id);
			ni.setUserName(userName);
			ni.setChinese(chinese);
			ni.setChineses(chineses);
			ni.setEnglishE(englishE);
			ni.setEnglish(english);
			ni.setJapanese(japanese);
			ni.setJapaneses(japaneses);
			ni.setPicture((picture.length()>4)?picture:null);
			ni.setLocation(inLatLng.replaceAll("[(*)]", ""));//去掉不要"()"符號，原始檔：(12.123,123.12)
			ni.setImportance(importance);
			ni.setUpdatedate(new Date());
			ni.setCreatedate(createdate);
			ni.setDeleteFlag("N");
			ni.setSentence(sentence);
			ni.setProperty(property);
			
			try {
				noteitDao.saveNoteit(ni);
				url = "InitModifyNoteitAction.do?id="+id;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "success_modify";
		}else {
			return "input";
		}
	}
		
	@SuppressWarnings("rawtypes")
	public String initModifyNoteit() {
		sessionMap.remove("noteitList");
		List noteitList = noteitDao.wordsPoolAll();
		//List noteitList = (List) sessionMap.get("noteitList");
		System.out.println("list="+noteitList.size());
		if (noteitList.size() > 0)

			for (int i = 0; i < noteitList.size(); i++) {
				Noteit tmp = ((Noteit) noteitList.get(i));
				if (tmp.getId() == id) {
					ni = tmp;
				}
			}
		sessionMap.remove("noteitList");
		return SUCCESS;
	}
	
	public String initDelDetail(){
		List noteitDeleteHistoryList = (List<Noteit>) sessionMap.get("noteitDeleteHistoryList");
		System.out.println("noteitDeleteHistoryList="+noteitDeleteHistoryList.size());
		if (noteitDeleteHistoryList.size() > 0)

			for (int i = 0; i < noteitDeleteHistoryList.size(); i++) {
				Noteit tmp = ((Noteit) noteitDeleteHistoryList.get(i));
				if (tmp.getId() == id) {
					ni = tmp;
				}
			}
		return SUCCESS;
	}
	
    public String deleteNoteit() throws Exception{
    	userName = (String) ServletActionContext.getRequest().getSession().getAttribute("loggedInUser");
    	
    	String idStr = String.valueOf(id);
    	System.out.println("delete_id:"+idStr+", userName="+userName);
    	
    	if(idStr.length()>0 && idStr!=null){
    		noteitDao.noteitDataDelete(id, userName);
    	}
		return "success";
    }
    public String multiSaveNoteit(){
		ServletActionContext.getRequest().getSession().getAttribute("loggedInUser");  
		userName = (String) ServletActionContext.getRequest().getSession().getAttribute("loggedInUser");  
		System.out.println("test for get UESR =" +userName);
		return "success";
	}
    
    public String InitNoteIT(){
		return SUCCESS;
	}
    
	public String aboutUs(){
		return "success";
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public Noteit getNi() {
		return ni;
	}
	public void setNi(Noteit ni) {
		this.ni = ni;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getEnglish() {
		return english;
	}
	public void setEnglish(String english) {
		this.english = english;
	}
	public String getChinese() {
		return chinese;
	}
	public void setChinese(String chinese) {
		this.chinese = chinese;
	}
	public String getChineses() {
		return chineses;
	}
	public void setChineses(String chineses) {
		this.chineses = chineses;
	}
	public String getJapaneses() {
		return japaneses;
	}
	public void setJapaneses(String japaneses) {
		this.japaneses = japaneses;
	}
	public String getJapanese() {
		return japanese;
	}
	public void setJapanese(String japanese) {
		this.japanese = japanese;
	}
	
	public String getEnglishE() {
		return englishE;
	}

	public void setEnglishE(String englishE) {
		this.englishE = englishE;
	}

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}

	public String getSentence() {
		return sentence;
	}

	public void setSentence(String sentence) {
		this.sentence = sentence;
	}

	public String getPicture() {
		return picture;
	}
	public void setPicture(String picture) {
		this.picture = picture;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
	public Date getCreatedate() {
		return createdate;
	}
	public void setCreatedate(Date createdate) {
		this.createdate = createdate;
	}
	public Date getUpdatedate() {
		return updatedate;
	}
	public void setUpdatedate(Date updatedate) {
		this.updatedate = updatedate;
	}
	public String getCheckDataIsNew() {
		return checkDataIsNew;
	}
	public void setCheckDataIsNew(String checkDataIsNew) {
		this.checkDataIsNew = checkDataIsNew;
	}
	public int getImportance() {
		return importance;
	}
	public void setImportance(int importance) {
		this.importance = importance;
	}
	public String getDeleteFlag() {
		return deleteFlag;
	}
	public void setDeleteFlag(String deleteFlag) {
		this.deleteFlag = deleteFlag;
	}
	public Date getDeletedate() {
		return deletedate;
	}
	public void setDeletedate(Date deletedate) {
		this.deletedate = deletedate;
	}
	public String getDeleteUserName() {
		return deleteUserName;
	}
	public void setDeleteUserName(String deleteUserName) {
		this.deleteUserName = deleteUserName;
	}
	public String getCreatedateBgnStr() {
		return createdateBgnStr;
	}

	public void setCreatedateBgnStr(String createdateBgnStr) {
		this.createdateBgnStr = createdateBgnStr;
	}

	public String getCreatedateEndStr() {
		return createdateEndStr;
	}

	public void setCreatedateEndStr(String createdateEndStr) {
		this.createdateEndStr = createdateEndStr;
	}

	public Date getCreatedateBgn() {
		return createdateBgn;
	}

	public void setCreatedateBgn(Date createdateBgn) {
		this.createdateBgn = createdateBgn;
	}

	public Date getCreatedateEnd() {
		return createdateEnd;
	}

	public void setCreatedateEnd(Date createdateEnd) {
		this.createdateEnd = createdateEnd;
	}

	public String getUpdatedateBgnStr() {
		return updatedateBgnStr;
	}

	public void setUpdatedateBgnStr(String updatedateBgnStr) {
		this.updatedateBgnStr = updatedateBgnStr;
	}

	public String getUpdatedateEndStr() {
		return updatedateEndStr;
	}

	public void setUpdatedateEndStr(String updatedateEndStr) {
		this.updatedateEndStr = updatedateEndStr;
	}

	public Date getUpdatedateBgn() {
		return updatedateBgn;
	}

	public void setUpdatedateBgn(Date updatedateBgn) {
		this.updatedateBgn = updatedateBgn;
	}

	public Date getUpdatedateEnd() {
		return updatedateEnd;
	}

	public void setUpdatedateEnd(Date updatedateEnd) {
		this.updatedateEnd = updatedateEnd;
	}

	public String getDeletedateBgnStr() {
		return deletedateBgnStr;
	}

	public void setDeletedateBgnStr(String deletedateBgnStr) {
		this.deletedateBgnStr = deletedateBgnStr;
	}

	public String getDeletedateEndStr() {
		return deletedateEndStr;
	}

	public void setDeletedateEndStr(String deletedateEndStr) {
		this.deletedateEndStr = deletedateEndStr;
	}

	public Date getDeletedateBgn() {
		return deletedateBgn;
	}

	public void setDeletedateBgn(Date deletedateBgn) {
		this.deletedateBgn = deletedateBgn;
	}

	public Date getDeletedateEnd() {
		return deletedateEnd;
	}

	public void setDeletedateEnd(Date deletedateEnd) {
		this.deletedateEnd = deletedateEnd;
	}

	public String getInLatLng() {
		return inLatLng;
	}

	public void setInLatLng(String inLatLng) {
		this.inLatLng = inLatLng;
	}

	@Override
	public void setRequest(Map<String, Object> requestMap) {
		this.requestMap = requestMap;
	}
	@Override
	public void setSession(Map<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}
}
